using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp;
using Volo.Abp.Application;
using Volo.Abp.AutoMapper;
using Volo.Abp.Caching;
using Volo.Abp.EventBus.Distributed;
using Volo.Abp.FluentValidation;
using Volo.Abp.Modularity;
using Volo.Abp.BackgroundWorkers;
using Volo.Abp.BackgroundJobs;
using Volo.Abp.Threading;
using Matrix.ServiceDiscovery.Services;
using Matrix.ServiceDiscovery.Entities;
using Matrix.ServiceDiscovery.Events;
using Matrix.ServiceDiscovery.Dtos;

namespace Matrix.ServiceDiscovery
{
    [DependsOn(
        typeof(MatrixServiceDiscoveryDomainModule),
        typeof(MatrixServiceDiscoveryApplicationContractsModule),
        typeof(AbpDddApplicationModule),
        typeof(AbpAutoMapperModule),
        typeof(AbpCachingModule),
        typeof(AbpDistributedEventBusModule),
        typeof(AbpBackgroundJobsModule),
        typeof(AbpFluentValidationModule)
    )]
    public class MatrixServiceDiscoveryApplicationModule : AbpModule
    {
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var services = context.Services;

            // 配置AutoMapper
            Configure<AbpAutoMapperOptions>(options =>
            {
                options.AddMaps<MatrixServiceDiscoveryApplicationModule>();
            });

            // 配置缓存
            Configure<AbpDistributedCacheOptions>(options =>
            {
                options.KeyPrefix = "Matrix:ServiceDiscovery";
            });

            // 注册CQRS服务
            services.AddTransient<ServiceDiscoveryQueryService>();
            services.AddTransient<ServiceDiscoveryCommandService>();
            services.AddTransient<ServiceDiscoveryCacheService>();

            // 配置FluentValidation
            services.AddValidatorsFromAssemblyContaining<CreateServiceInfoValidator>();

            // 配置事件处理器
            services.AddTransient<IDistributedEventHandler<ServiceChangedEto>, ServiceDiscoveryEventHandler>();
            services.AddTransient<IDistributedEventHandler<ServiceInstanceChangedEto>, ServiceDiscoveryEventHandler>();
            services.AddTransient<IDistributedEventHandler<LoadBalancingConfigChangedEto>, ServiceDiscoveryEventHandler>();
        }

        public override async Task OnApplicationInitializationAsync(ApplicationInitializationContext context)
        {
            // 启动后台任务
            await context.ServiceProvider
                .GetRequiredService<IBackgroundWorkerManager>()
                .StartAsync();
        }
    }

    /// <summary>
    /// 服务发现事件处理器
    /// </summary>
    public class ServiceDiscoveryEventHandler :
        IDistributedEventHandler<ServiceChangedEto>,
        IDistributedEventHandler<ServiceInstanceChangedEto>,
        IDistributedEventHandler<LoadBalancingConfigChangedEto>
    {
        private readonly ServiceDiscoveryCacheService _cacheService;
        private readonly ILogger<ServiceDiscoveryEventHandler> _logger;

        public ServiceDiscoveryEventHandler(
            ServiceDiscoveryCacheService cacheService,
            ILogger<ServiceDiscoveryEventHandler> logger)
        {
            _cacheService = cacheService;
            _logger = logger;
        }

        public async Task HandleEventAsync(ServiceChangedEto eventData)
        {
            _logger.LogInformation("处理服务变更事件: {EventType} - {ServiceName}",
                eventData.EventType, eventData.ServiceName);

            // 清理相关缓存
            await _cacheService.InvalidateServiceCachesAsync(eventData.ServiceId, eventData.ServiceName);
        }

        public async Task HandleEventAsync(ServiceInstanceChangedEto eventData)
        {
            _logger.LogInformation("处理实例变更事件: {EventType} - {ServiceName}/{InstanceId}",
                eventData.EventType, eventData.ServiceName, eventData.InstanceIdStr);

            // 清理相关缓存
            await _cacheService.InvalidateInstanceCachesAsync(
                eventData.ServiceId,
                eventData.ServiceName,
                eventData.InstanceId);
        }

        public async Task HandleEventAsync(LoadBalancingConfigChangedEto eventData)
        {
            _logger.LogInformation("处理负载均衡配置变更事件: {EventType} - {ServiceName}",
                eventData.EventType, eventData.ServiceName);

            // 清理相关缓存
            await _cacheService.InvalidateServiceCachesAsync(eventData.ServiceId, eventData.ServiceName);
        }
    }
}